package com.example.core.queue.distuptor.config;

import com.example.core.queue.distuptor.event.QueueEvent;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.WorkHandler;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;

/**
 * 构建队列信息
 */
public class QueueRingBuffer {

  private   int bufferSize = DisruptorConfig.BUFFERSIZE;

  //队列唯一编号
  private String queueId;

  //队列实体
  private final Disruptor<QueueEvent> disruptor;

    /**
     * 构建队列
     * @param eventFactory
     */
  public QueueRingBuffer(final EventFactory<QueueEvent> eventFactory){
      this.queueId= DisruptorConfig.DEFULTDISRUPTORID;
      disruptor= new Disruptor<>(eventFactory, bufferSize, DaemonThreadFactory.INSTANCE);
  }

    /**
     *  构建队列
     * @param queueId
     * @param eventFactory
     */
  public QueueRingBuffer(String queueId,final EventFactory<QueueEvent> eventFactory){
      this.queueId= queueId;
      disruptor=  new Disruptor<>(eventFactory, bufferSize, DaemonThreadFactory.INSTANCE);
  }


    /**
     * 消费者
     * @param handlers
     */
  public void setConsumerListener(final EventHandler<? super QueueEvent>... handlers){
        disruptor.handleEventsWith(handlers);
  }
    /**
     * 消费者
     * @param workHandlers
     */
  public void setConsumerListener(final WorkHandler<QueueEvent>... workHandlers){
        disruptor.handleEventsWithWorkerPool(workHandlers);
  }


    /**
     * 启动队列
     */
  public void start(){
      if(disruptor!=null){
          disruptor.start();
          BufferData.init().put(this.queueId,disruptor.getRingBuffer());
      }
  }



















}
